package com.mioto.ld.communication.websocket.util;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.StrBuilder;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.mioto.ld.communication.websocket.model.SendCmdEnum;
import com.mioto.ld.communication.websocket.model.WsSendMessage;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * @author mioto-qinxj
 * @date 2024/5/16
 * @desc
 */
@Slf4j
public class MessageSendUtil {

    /**
     * 向指定通道发送消息
     * @param channel
     * @param sendCmdEnum
     */
    public static void send(Channel channel, SendCmdEnum sendCmdEnum){
        send(channel,new WsSendMessage(sendCmdEnum));
    }


    public static void send(Channel channel,WsSendMessage message){
        String text = JSONUtil.parse(message).toString();
        log.info("send websocket message - {}",text);
        channel.writeAndFlush(new TextWebSocketFrame(text));
    }

    public static void send(String clientId,WsSendMessage message){
        List<Channel> channels = WsChannelUtil.get(clientId);
        if (CollUtil.isNotEmpty(channels)){
            for (Channel channel : channels) {
                channel.writeAndFlush(new TextWebSocketFrame(JSONUtil.parse(message).toString()));
                log.info("send websocket message - {} to clientId - {}",JSONUtil.parse(message),clientId);
            }
        }
    }
}
